package org.stvd.core.util;

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.net.util.Base64;

public class Des {
    /**
     * DES加密
     * 
     * @parameter message：需要加密的消息
     * @parameter key：秘钥
     * @return 加密后的字符串
     */
    public static String encrypt(String message, String key) throws Exception {
        // 对字符串进行URL编码
        // String jiami=java.net.URLEncoder.encode(message,
        // "utf-8").toLowerCase();
        String jiami = java.net.URLEncoder.encode(message, "utf-8");
        jiami = encryptBASE64(jiami);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] bs = cipher.doFinal(jiami.getBytes("UTF-8"));
        return toHexString(bs);
        // return toHexString(bs).toUpperCase();
    }

    /**
     * DES解密
     * 
     * @parameter message：需要解密的消息
     * @parameter key：秘钥
     * @return 解密后的字符串
     */
    public static String decrypt(String message, String key) throws Exception {
        byte[] bytesrc = convertHexString(message);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] retByte = cipher.doFinal(bytesrc);
        String ret = new String(retByte, "UTF-8");
        // 先以base64进行解密，然后用URL进行解码
        // ret =
        // java.net.URLDecoder.decode(decryptBASE64(ret).toLowerCase(),"utf-8");
        ret = java.net.URLDecoder.decode(decryptBASE64(ret), "utf-8");
        return ret;
    }

    public static byte[] convertHexString(String ss) {
        byte digest[] = new byte[ss.length() / 2];
        for (int i = 0; i < digest.length; i++) {
            String byteString = ss.substring(2 * i, 2 * i + 2);
            int byteValue = Integer.parseInt(byteString, 16);
            digest[i] = (byte) byteValue;
        }
        return digest;
    }

    public static String toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }
        return hexString.toString();
    }

    /**
     * 以base64对字符串加密
     * 
     * @param s
     * @return
     */
    public static String encryptBASE64(String s) {
        String ret = "";
        try {
            byte[] b = s.getBytes("UTF-8");
            ret = new String(Base64.encodeBase64(b), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 以base64对字符串解密
     * 
     * @param s
     * @return
     */
    public static String decryptBASE64(String s) {
        byte[] ret = {};
        try {
            ret = Base64.decodeBase64(s.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            return new String(ret, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * Des(Base64(flatid),密钥),先进行base64加密，再进行des加密
     * 
     * @param source
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptDesBase64(String source, String key) throws Exception {
        String base64Str = encryptBASE64(source);
        System.out.println("base64Str : " + base64Str);
        String desStr = encrypt(base64Str, key);
        System.out.println("desStr : " + desStr);
        return desStr;
    }

    /**
     * Des(Base64(flatid),密钥),先进行des解密，在进行base64解密
     * 
     * @param source
     * @param key
     * @return
     * @throws Exception
     */
    public static String decryptDesBase64(String source, String key) throws Exception {

        String base64Str = encryptBASE64(source);
        System.out.println("base64Str : " + base64Str);

        String desStr = decrypt(source, key);
        System.out.println("desStr : " + desStr);

        return base64Str;
        // return decryptBASE64(decrypt(source,key));
    }

}